﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Cofe.Core;
using Cofe.Core.Logger;
using Cofe.Core.Script;

namespace Cofe.Web.Feed
{
    public class FeedUpdater<T> : IFeedUpdater<T>, IEventListener<T>
        where T : EventArgs
    {
        #region Constructor

        public FeedUpdater(IFeedService<T> feedService)
        {
            _feedService = feedService;
        }

        #endregion

        #region Methods

        public void Start()
        {
            if (_cts != null && !_cts.IsCancellationRequested)
                _cts.Cancel();

            _cts = new CancellationTokenSource();
            CofeServices.TaskManager.StartRepeat((c) =>
                {
                    if (!c.IsCancellationRequested)
                        Update();
                }, TimeSpan.FromSeconds(5), _cts.Token, 1);

            CofeServices.EventHub.RegisterEventListener(this);
            
        }

        public void Stop()
        {
            if (_cts != null)
                _cts.Cancel();
        }

        public void DispatchEvent(IEnumerable<IEventLog<T>> eventsRecorded)
        {
            foreach (var e in eventsRecorded)
                AddEvent(e);
        }


        public void AddEvent(IEventLog<T> eventLog)
        {
            Buffer.Add(eventLog);
        }

        public void Update()
        {
            var queue = new Queue<IScriptCommand>();
            var pd = ScriptParameterDic.FromParameterDic(ParameterDic.Empty);
            pd.AddOrUpdate("EventBuffer", Buffer);
            queue.Enqueue(new QueryingEvents<T>());
            CofeServices.Script.RunnerSpawner.Run(queue, pd);
        }


        public void Dispose()
        {
            _cts.Cancel();
        }

        public EventBuffer<T> Buffer { get { return _buffer; } }
        
        #endregion

        #region Data

        EventBuffer<T> _buffer = new EventBuffer<T>();
        IFeedService<T> _feedService;
        CancellationTokenSource _cts;

        #endregion

        #region Public Properties

        public CancellationToken CancellationToken { get { return _cts.Token; } }
        
        #endregion



        
       
    }
}
